# -*- coding: utf-8 -*-
import time
import requests
from FeiShu.FeishuMsg import feishu_msg
from config.config import NOW_ENV, log_separator
from core.DataReplace import get_url
from utils.logger import log

"""
HTTP接口请求
"""


class HttpRequest:
    # 创建一个会话
    def __init__(self):
        self.sess = requests.session()
        self.response_time_ms = 0

    def __ceil__(self, yaml_data, env):
        return self.session_request(yaml_data, env)

    # 使所有用例都在同一个会话执行
    def session_request(self, data, env=NOW_ENV):
        log.info(log_separator + "Session" + log_separator)
        # 飞书消息获取当前执行的用例
        feishu_msg.current_case = data['name']
        domain_name = get_url(env)
        log.info("读取yaml文件中的请求方式")
        try:
            if data["method"].lower() in ["get", "post", "put", "delete"]:
                if 'http' not in data["url"]:
                    url = domain_name + data["url"]
                else:
                    url = data["url"]
                log.info("url组装完成: %s" % url)
                log.info("开始执行请求.")
                log.info("记录请求开始时间.")
                start_timestamp = time.time()  # 记录接口调用开始时间
                res = self.sess.request(data["method"], url, **data["requests"])
                # 计算出接口执行的时间
                self.response_time_ms = round((time.time() - start_timestamp) * 1000, 2)
                log.info("请求完成.")
                log.info(
                    "接口请求时间为: %sms" % str(self.response_time_ms))
                return res
            else:
                msg = '请求方式不正确.'
                log.info(msg)
                raise ValueError(msg)
        except requests.exceptions.ConnectionError:
            result = False
            msg = '请求超时！'
            expected_msg = '正常请求'
            log.error("连接失败，断言失败!!")
            feishu_msg.get_msg_body(result, '', expected_msg, '',
                                    '', msg=msg)
            raise AssertionError("连接失败，断言失败!!")
